package com.zjs.servlet;

import com.zjs.bean.Users;
import com.zjs.service.UsersService;
import com.zjs.service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        if ("login".equals(method)) {
            login(req, resp);
        } else if ("loginOut".equals(method)) {
            loginOut(req, resp);
        }
    }

    /**
     * 注销
     *
     * @throws IOException
     */
    protected void loginOut(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 获取当前会话
        HttpSession session = request.getSession(false);

        if (session != null) {
            // 清除会话中的所有属性
            session.invalidate();
            // 可选：发送一个过期的cookie来确保客户端也清除会话ID
            Cookie sessionCookie = new Cookie("JSESSIONID", "");
            sessionCookie.setMaxAge(0); // 设置为0表示立即过期
            sessionCookie.setPath("/");
            response.addCookie(sessionCookie);
        }
        //重定向到登录页面
        response.sendRedirect("/login.jsp");
    }

    /**
     * 登录
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户信息
        String loginName = req.getParameter("loginName");
        String password = req.getParameter("password");
        //判断登录信息是否正确
        UsersService usersService = new UsersServiceImpl();
        Users user = usersService.getUser(loginName, password);
        if (user != null) {
            //如果登录信息正确，跳转到主页并存session
            req.getSession().setAttribute("user", user);
            //跳转到主页
            resp.sendRedirect("/index.jsp");
        } else {
            //如果登录信息不正确，跳转到登录页面
            resp.sendRedirect("/login.jsp");
        }
    }
}
